﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using Newtonsoft.Json;
using System.Text;
using System.Data;


namespace ReportTracking.Services
{
    /// <summary>
    /// Summary description for PL2
    /// </summary>
    public class PL9G : IHttpHandler, IReadOnlySessionState
    {
        ReportTracking.ReportTrackingDTT.TrackingReportClient rptrk = new ReportTracking.ReportTrackingDTT.TrackingReportClient();
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            /*string sDVKD = context.Request.QueryString["dvkd"];
            DateTime sfd = Convert.ToDateTime(context.Request.QueryString["fd"]);
            DateTime std = Convert.ToDateTime(context.Request.QueryString["today"]);
            int nReportType = Convert.ToInt32(context.Request.QueryString["reporttype"]);*/
            
            string sparam = context.Request.QueryString["param"];
            Dictionary<string, string> value = JsonConvert.DeserializeObject<Dictionary<string, string>>(sparam);
            string sDVKD = value["dvkd"];
            DateTime sfd = Convert.ToDateTime(value["fd"]);
            DateTime std = Convert.ToDateTime(value["td"]);
            int nReportType = Convert.ToInt32(value["reporttype"]);

            int page = Convert.ToInt32(context.Request.QueryString["page"]);
            int nRows = Convert.ToInt32(context.Request.QueryString["rows"]);
            string sReload = HttpContext.Current.Request.Cookies["bRequest"].Value;
            string[] sArrDVDK = sDVKD.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            int nTotal = 0;
            int nPage = 0;
            StringBuilder sData = new StringBuilder();
            string sTable = "";

            if (sReload == "0")
            {
                string[] arrLPT = new string[] { };
                float[] arrSpeed = new float[] { };
                context.Session["Data"] = null;
                context.Session["InfoReprot"] = null;
                if (sArrDVDK.Length > 0)
                {
                    if (sArrDVDK[0] == "All")
                    {
                        sArrDVDK = null;
                    }
                }
                sTable = Newtonsoft.Json.JsonConvert.SerializeObject(GetData(sfd, std, ref nTotal, ref nPage, sArrDVDK, (page - 1) * nRows, nRows));
                InfoReport inforeport = new InfoReport(String.Format("{0:d/M/yyyy}", sfd), String.Format("{0:d/M/yyyy}", std), sArrDVDK, nTotal, nReportType, "");
                context.Session["InfoReprot"] = inforeport;
            }
            else
            {
                DataTable tb = (DataTable)context.Session["Data"];
                sTable = Newtonsoft.Json.JsonConvert.SerializeObject(DivPage(ref nTotal, ref nPage, (page - 1) * nRows, nRows));

            }


            /*Dung tam */
            /*
            sTable = Newtonsoft.Json.JsonConvert.SerializeObject(GetData(ref nTotal, ref nPage, nRows));
            InfoReport inforeport = new InfoReport(String.Format("{0:d/M/yyyy HH:mm:ss}",sfd),String.Format("{0:d/M/yyyy HH:mm:ss}",std), sArrDVDK, nTotal, nReportType, "");
            context.Session["InfoReprot"] = inforeport;
             */
            /*  Ket thuc dung tam */
            sData.Append("{");
            sData.Append("page:");
            sData.Append(page);
            sData.Append(",");
            sData.Append("total:");
            sData.Append(nPage);
            sData.Append(",");
            sData.Append("records:");
            sData.Append(nTotal);
            sData.Append(",");
            sData.Append("rows:");
            sData.Append(sTable);
            sData.Append("}");
            context.Response.Write(Newtonsoft.Json.JsonConvert.DeserializeObject(sData.ToString()));
        }
        private DataTable GetData(DateTime sFromDay, DateTime sToDay, ref  int total,  ref int nPage, string[] sArrDVDK, int nFromRecords, int nNumberRecords)
        {
            try
            {
                DataTable tb = rptrk.GetReportOverTimeDriving(sArrDVDK, sFromDay, sToDay).Tables[0];
                HttpContext.Current.Session["Data"] = tb;
                total = tb.Rows.Count;
                nPage = Utilities.PageNumber(total, nNumberRecords);
                if (tb.Rows.Count > 0)
                {
                    IEnumerable<DataRow> results = (from myRow in tb.AsEnumerable().Skip(nFromRecords).Take(nNumberRecords)
                                                    select myRow);

                    return ReturnData(results);
                }
            }
            catch (System.Exception ex)
            {
                return null;
            }


            return null;
        }

        private DataTable DivPage(ref int nTotal, ref int nPage, int fromreocrds = 0, int torecords = 100)
        {
            DataTable tb = (DataTable)HttpContext.Current.Session["Data"];
            nTotal = tb.Rows.Count;
            nPage = Utilities.PageNumber(nTotal, torecords);
            if (tb.Rows.Count > 0)
            {
                IEnumerable<DataRow> results = (from myRow in tb.AsEnumerable().Skip(fromreocrds).Take(torecords)
                                                select myRow);

                return ReturnData(results);
            }
            return null;


        }

        private DataTable ReturnData(IEnumerable<DataRow> dtr)
        {
            DataTable tb = CreateDatatable();
            foreach (var dr in dtr)
            {
                tb.Rows.Add( dr["BusinessUnitType"], Utilities.EditString(String.Format("{0:d/M/yyyy}", dr["Date"]), @"\s", "</br>", 2),
                     String.Format("{0:0.00}", dr["TotalDistance"]), 1, 2, 3,
                 4,"","","",7,"","", Utilities.EditString(dr["Note"].ToString(), @"\s", "</br>", 10));
            }
            return tb;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        private static DataTable CreateDatatable()
        {
            DataTable tb = new DataTable();
            
            tb.Columns.Add("LHHD", typeof(string));
            tb.Columns.Add("NGAYHD", typeof(string));
            tb.Columns.Add("TKM", typeof(double));
            tb.Columns.Add("SLQT10", typeof(int));
            tb.Columns.Add("SLQT10-20", typeof(int));
            tb.Columns.Add("SLQT20", typeof(int));
            tb.Columns.Add("TSLXCSHT", typeof(int));
            tb.Columns.Add("TGN5", typeof(string));
            tb.Columns.Add("TG5-10", typeof(string));
            tb.Columns.Add("TGL10", typeof(string));
            tb.Columns.Add("SLXDMC", typeof(int));
            tb.Columns.Add("TGLT4H", typeof(string));
            tb.Columns.Add("TGLT10H", typeof(string));
            tb.Columns.Add("Note", typeof(string));
            tb.Dispose();
            return tb;

        }
        private  static string FormatCoordinate(object dCoodinate)
        {
            string s = "";
            string[] sPlit = dCoodinate.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            s = String.Format("{0:0.000000}", Convert.ToDouble(sPlit[0])) + " " + String.Format("{0:0.000000}", Convert.ToDouble(sPlit[1]));
            return s;

        }
    }
}